import jwt from 'jsonwebtoken'
import cookie from 'cookie'
import {User} from '@/common/api/model'
const gettoken = (user)=>{
    const token = jwt.sign({
        account:user.account,
        nickname:user.nickname
    },process.env.JWT_SECRET, { expiresIn: '3 days' });
    return token
}
export default async function handler(req, res) {
    const query = req.body;
    //先判断有没有昵称有昵称是创建新的
    if(query.nickname){
        const newZhanghao = new User(query)
        newZhanghao.save().then(saveZhanghao=>{
            const token = gettoken(saveZhanghao)
            res.setHeader('Set-Cookie',cookie.serialize('token',token,{
                httpOnly: true,
                path: '/',
                maxAge: 60 * 60 * 24 * 3
            }))
            res.status(200);
            res.json({
                code:1,
                data:{
                    
                },
                msg: "创建成功"
            })
        }).catch(err=>{
            res.status(200).json({
                code:-1,
                data:{
                    
                },
                msg: "创建新账号失败"
            })
        })
    }else{
        User.findOne({account:query.account}).then(user=>{
            if(user){
                //查到用户
                if(user.password == query.password){
                    const token = gettoken(user)
                    res.status(200);
                    res.setHeader('Set-Cookie',cookie.serialize('token',token,{
                        httpOnly: true,
                        path: '/',
                        maxAge: 60 * 60 * 24 * 3
                    }))
                    // const payload = jwt.verify(token, process.env.JWT_SECRET)
                    // console.log(100,payload);
                    res.json({
                        code:1,
                        data:{
                            ...user,
                            token:token
                        },
                        msg: "登录成功"
                    })
                }else{
                    res.status(200).json({
                        code:-1,
                        data:{},
                        msg: "密码错误"
                    })
                }
            }else{
                //没有查到用户
                res.status(200).json({
                    code:-2,
                    data:{
                        
                    },
                    msg: "为您创建新用户，请填写昵称"
                })
            }
        })
    }
}